﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.Domain;
using Casamiel.Domain.Entity;

using Dapper;
using Smooth.IoC.Repository.UnitOfWork;
using Smooth.IoC.UnitOfWork.Interfaces;

namespace Casamiel.Infrastructure.Repositories
{
	/// <summary>
	/// 
	/// </summary>
    public sealed class InvoiceRepository : BaseRepository<BaseInvoice, long>, IInvoiceRepository, IRepositoryExt<BaseInvoice, long>, IRepository<BaseInvoice, long>
    {
        // Methods
        public InvoiceRepository(IDbFactory factory) : base(factory)
        {
        }

        public async   Task<PagingResult<BaseInvoice>> GetListAsnyc<TSession>(string Mobile, int pageIndex, int pageSize) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                PagingResult<BaseInvoice> result = new PagingResult<BaseInvoice>
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };
                int total = 0;
                var sql = GetSelectSQL($"{Sql.Table<BaseInvoice>(session.SqlDialect)}", $"Mobile=@Mobile", "ID desc", pageIndex, pageSize);
                string countsql = $"select count(0) from {Sql.Table<BaseInvoice>(session.SqlDialect)} where Mobile=@Mobile";

                total = await session.QueryFirstAsync<int>(countsql,new{Mobile})
                    .ConfigureAwait(false);
				var list = await session.QueryAsync<BaseInvoice>(sql.Item1, new { begin = sql.Item2, end = sql.Item3,Mobile })
                    .ConfigureAwait(false);
                result.Data = list.ToList();
                result.Total = total;
                return result;
            }
        }
    }
}
